package cn.jsxz.common.utils;

import cn.jsxz.common.utils.JiaMi.MD5Util;
import cn.jsxz.dto.Result;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.setting.dialect.Props;
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class PrintUtil {

    /**
     * 获取Access TokenUtil
     *
     * @param @return 参数
     * @return JSONObject    返回类型
     * @throws
     * @Title: getPrintToken
     * @Description: TODO
     */
    public JSONObject getPrintToken() {
        Props props = new Props("workConfig.properties", "utf-8");
        String client_id = props.getStr("client_id");// 打印机应用id
        String timestamp = String.valueOf(System.currentTimeMillis());// 时间戳
        String client_secret = props.getStr("client_secret");// 应用密钥
        String grant_type = "client_credentials";// 授与方式（固定为'client_credentials'）
        String scope = "all";// 授权权限，传all
        String id = RandomUtil.randomUUID();// 36位随机字符串
        String str = client_id + timestamp + client_secret;// 拼接签名参数
        String sign = MD5Util.MD5Encode(str, null).toLowerCase();// 获取签名
        String result = "";
        JSONObject json = new JSONObject();
        Map<String, String> params = new HashMap<String, String>();
        params.put("client_id", client_id);
        params.put("grant_type", grant_type);
        params.put("sign", sign);
        params.put("scope", scope);
        params.put("timestamp", timestamp);
        params.put("id", id);
        HttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(props.getStr("AccessToken"));
        ArrayList<NameValuePair> pam = new ArrayList<NameValuePair>();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            pam.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        try {
            post.setEntity(new UrlEncodedFormEntity(pam, "UTF-8"));
            HttpResponse response = client.execute(post);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity, "UTF-8");
            System.out.println(result + "第一次请求");
            json = this.getPrintRefreshToken(result);
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 使用Refresh token更新Access TokenUtil
     *
     * @param @param  content
     * @param @return 参数
     * @return JSONObject    返回类型
     * @throws
     * @Title: getPrintRefreshToken
     * @Description: TODO
     */
    public JSONObject getPrintRefreshToken(String content) {
        Props props = new Props("workConfig.properties", "utf-8");
        JSONObject jsonBody = new JSONObject(new JSONObject(JSON.parse(content)).get("body"));
        Map<String, String> params = new HashMap<String, String>();
        String timestamp = String.valueOf(System.currentTimeMillis());
        String str = props.getStr("client_id") + timestamp + props.getStr("client_secret");// 拼接签名参数
        String sign = MD5Util.MD5Encode(str, null).toLowerCase();// 获取签名
        params.put("client_id", props.getStr("client_id"));
        params.put("grant_type", "refresh_token");
        params.put("scope", "all");
        params.put("sign", sign);
        params.put("refresh_token", jsonBody.get("refresh_token").toString());
        params.put("timestamp", timestamp);
        params.put("id", RandomUtil.randomUUID());
        String result = "";
        JSONObject obj = null;
        ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            param.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        HttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(props.getStr("AccessToken"));
        try {
            post.setEntity(new UrlEncodedFormEntity(param, "UTF-8"));
            HttpResponse response = client.execute(post);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity, "UTF-8");
            System.out.println(result + "第二次请求");
            obj = new JSONObject(new JSONObject(JSON.parse(result)).get("body"));
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        }
        return obj;
    }


    /**
     * @auther: Zy
     * @method printAccredit
     * 功能描述: 易联云打印机授权
     * @params: []
     * @return: * @return : cn.jsxz.dto.Result
     */
    public Result printAccredit() {
        Props props = new Props("workConfig.properties", "utf-8");
        String client_id = props.getStr("client_id");// 打印机应用id
        String access_token = "d66aa7a569db497c9f60a49329a3ba7a";//授权的token 必要参数
        String machine_code = props.getStr("machine_code");//易联云打印机终端号
        String timestamp = String.valueOf(System.currentTimeMillis());// 时间戳
        String str = client_id + timestamp + props.getStr("client_secret");// 拼接签名参数
        String sign = MD5Util.MD5Encode(str, null).toLowerCase();// 获取签名
        Map<String, String> params = new HashMap<String, String>();
        params.put("client_id", client_id);//易联云颁发给开发者的应用ID 非空值
        params.put("machine_code", machine_code);//易联云打印机终端号
        params.put("msign", props.getStr("msign"));//易联云终端密钥
        params.put("access_token", access_token);//授权的token 必要参数  《需要查出来》
        params.put("sign", sign);
        params.put("id", RandomUtil.randomUUID());
        params.put("timestamp", timestamp);
//		params.put("phone", phone);
//		params.put("print_name", print_name);
        HttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(props.getStr("addprinter"));
        String result = "";
        JSONObject obj = null;
        ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            param.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        try {
            post.setEntity(new UrlEncodedFormEntity(param, "UTF-8"));
            HttpResponse response = client.execute(post);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity, "UTF-8");
            System.out.println(result);
            obj = new JSONObject(JSON.parse(result));
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        }
        if (obj.get("error_description").equals("success")) {
            return ResultUtil.success();
        } else {
            return ResultUtil.error("新增失败");
        }
    }

    /**
     * 易联云打印机发送打印信息
     *
     * @param machineCode
     * @return
     */
    public static void prientContent(String content, String machineCode) {
        Props props = new Props("developer.properties", "utf-8");
        String client_id = props.getStr("client_id");// 打印机应用id
        String access_token = props.getStr("access_token");// 授权的token 必要参数
        String timestamp = String.valueOf(System.currentTimeMillis());// 时间戳
        String str = client_id + timestamp + props.getStr("client_secret");// 拼接签名参数
        String sign = MD5Util.MD5Encode(str, null).toLowerCase();// 获取签名
        Map<String, String> params = new HashMap<String, String>();
        params.put("client_id", client_id);// 打印机应用id
        params.put("access_token", access_token);// 授权的token 必要参数
        params.put("machine_code", machineCode);//打印机code码
        params.put("content", content);//打印内容
        params.put("origin_id", "");// 商户系统内部订唯一单号
        params.put("sign", sign);// 获取签名
        params.put("id", RandomUtil.randomUUID());
        params.put("timestamp", timestamp);// 时间戳
        System.out.println(params);
        HttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(props.getStr("printUrl"));
        ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            param.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        try {
            post.setEntity(new UrlEncodedFormEntity(param, "UTF-8"));
            HttpResponse response = client.execute(post);
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity, "UTF-8");
            System.out.println(result);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
}
